package cn.tnar.yunpark.util;

import io.netty.buffer.ByteBuf;

import java.nio.ByteBuffer;
import java.security.MessageDigest;

/**
 * Created by tieh on 2016/9/24.
 */
public class Util {
    final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();

    public static String toHex(byte[] bytes) {
        return toHex(bytes, bytes.length);
    }

    public static String toHex(byte[] bytes, int len) {
        char[] hexChars = new char[len * 2];
        for (int j = 0; j < len; j++) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }

    public static String toHex(ByteBuffer buf, int len) {
        StringBuilder sb = new StringBuilder();
        int start = buf.position();
        for (int i = start; i < start + len; i++) {
            sb.append(String.format("%02x", buf.get(i)));
        }
        return sb.toString();
    }

    public static String toHex(ByteBuffer buf) {
        return toHex(buf, buf.limit());
    }

    public static byte[] hexToBytes(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i+1), 16));
        }
        return data;
    }

    public static String toHex(ByteBuf buf, int len) {
        StringBuilder sb = new StringBuilder();
        int start = buf.readerIndex();
        for (int i = start; i < start + len; i++) {
            sb.append(String.format("%02x", buf.getByte(i)));
        }
        return sb.toString();
    }

    public static String toHex(ByteBuf buf) {
        return toHex(buf, buf.readableBytes());
    }


    /**
     * MD5编码
     *
     * @param s 原始字符串
     * @return MD5值
     */
    public static String md5(String s) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] ba = s.getBytes("UTF-8");
            return toHex(md.digest(ba));
        } catch (Exception e) {
            return "";
        }
    }

}
